import * as api from '@/services/admin';
import * as utils from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef } from 'react';
import { history, Link, useModel } from 'umi';

const getLoginInfo = (admin: API.Admin, lastLogin: boolean) => {
  let info = '';
  if (lastLogin) {
    if (admin.lastLoginTime) {
      info += `${utils.formatUtcToLocal(admin.lastLoginTime)}`;
    }

    if (admin.lastLoginIp) {
      info += `[${admin.lastLoginIp} : ${
        admin.lastLoginArea ? admin.lastLoginArea : ''
      }]`;
    }
  } else {
    if (admin.loginTime) {
      info += `${utils.formatUtcToLocal(admin.loginTime)}`;
    }

    if (admin.loginIp) {
      info += `[${admin.loginIp} : ${admin.loginArea ? admin.loginArea : ''}]`;
    }
  }

  return info;
};

const List: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const handleRemove = async (id: number) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.Admin>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '用户名',
      width: 180,
      dataIndex: 'username',
      sorter: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '登录信息',
      dataIndex: 'loginTime',
      sorter: true,
      render: (_, record) => {
        return (
          <>
            <span>{getLoginInfo(record, false)}</span>
            <br />
            <span>{getLoginInfo(record, true)}</span>
          </>
        );
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('admin_update')) {
          cmps.push(
            <Link key="update" to={`/system/admin/update/${record.id}`}>
              编辑
            </Link>,
          );
        }
        if (hasRight('admin_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }
        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        columnEmptyText={''}
        actionRef={actionRef}
        columns={columns}
        search={false}
        toolBarRender={() => {
          if (!hasRight('admin_create')) {
            return [];
          }

          return [
            <Button
              type="primary"
              key="create"
              onClick={() => {
                history.push(`/system/admin/create`);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ];
        }}
        pagination={{
          defaultPageSize: 60,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
        }}
        request={api.list}
      />
    </PageContainer>
  );
};

export default List;
